import cv2
import myfuncs as mf


class Template:
	originTemplate = None
	resizedTemplate = None
	originTemplateSize = ()
	resizedTemplateSize = ()
	outputSize = ()
	grayTemplate = None
	binaryTemplate = None
	templateContours = None
	templateROIs = {}

	def __init__(self, templatePath, singleTemplateSize, outputSize):
		singleTemplateHeight, singleTemplateWidth = singleTemplateSize
		self.outputSize = outputSize
		self.originTemplate = cv2.imread(templatePath)
		originHeight, originWidth, _ = self.originTemplate.shape
		rowCount, columnCount = int((originHeight/singleTemplateHeight).__round__(0)), int((originWidth/singleTemplateWidth).__round__(0))
		self.resizedTemplate = mf.resize(self.originTemplate.copy(), width=1024)
		self.resizedTemplateSize = (int((self.resizedTemplate.shape[0]/rowCount).__round__(0)), int((self.resizedTemplate.shape[1]/columnCount).__round__(0)))
		self.originTemplateSize = singleTemplateSize
		self.templateROIs = {}
		self.templateInitialize()

	@staticmethod
	def cvShow(imgDict):
		mf.showImages(imgDict)
		mf.waitEnd()

	@staticmethod
	def getContours(src):
		contours, hierarchy = cv2.findContours(src.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
		return contours

	@staticmethod
	def sortContours(contours, method="left-to-right"):
		return mf.sortContours(contours, method)[0]

	def templateInitialize(self):
		self.grayTemplate = cv2.cvtColor(self.resizedTemplate, cv2.COLOR_BGR2GRAY)
		self.binaryTemplate = cv2.threshold(self.grayTemplate, 127, 255, cv2.THRESH_BINARY_INV)[1]

		fullHeight, fullWidth, _ = self.resizedTemplate.shape
		singleHeight, singleWidth = self.resizedTemplateSize
		for (row, y) in enumerate(range(0, fullHeight, singleHeight)):
			for (column, x) in enumerate(range(0, fullWidth, singleWidth)):
				x, y, w, h = x, y, singleWidth, singleHeight
				outputSize = (self.outputSize[1], self.outputSize[0])
				roi = self.binaryTemplate[y:y + h, x:x + w]
				roi = cv2.resize(roi, outputSize)
				self.templateROIs[(column, row)] = roi

	def getTemplates(self):
		return self.templateROIs

	def getTemplateSize(self):
		return self.originTemplateSize
